package secret

import (
	"encoding/base64"
	"fmt"
	"strings"
	"time"

	"github.com/google/uuid"
	"github.com/infraboard/mcube/crypto/cbc"
)

func NewSecretSet() *SecretSet {
	return &SecretSet{
		Items: []*Secret{},
	}
}

func (s *SecretSet) Add(item *Secret) {
	s.Items = append(s.Items, item)
}
func NewMeta() *Meta {
	return &Meta{
		Id:       uuid.New().String(),
		CreateAt: time.Now().Unix(),
	}
}

func NewCreateSecretRequest() *CreateSecretRequest {
	return &CreateSecretRequest{
		Enabled: true,
	}
}

// 脱敏
func (i *CreateSecretRequest) Desense() {
	i.ApiSecret = "****"
}

func NewSecret(in *CreateSecretRequest) *Secret {
	return &Secret{
		Meta: NewMeta(),
		Spec: in,
	}
}
func New() *Secret {
	return &Secret{
		Meta: &Meta{},
		Spec: &CreateSecretRequest{},
	}
}
func (s *Secret) TableName() string {
	return "secrets"
}
func NewQuerySecretRequest() *QuerySecretRequest {
	return &QuerySecretRequest{}
}

func NewDescribeSecretRequest() *DescribeSecretRequest {
	return &DescribeSecretRequest{}
}

// 加密
func (s *Secret) EncryptAPISecret(key string) error {
	// 判断文本是否已经加密
	if strings.HasPrefix(s.Spec.ApiSecret, CIPHER_TEXT_PREFIX) {
		return fmt.Errorf("文本已加密，无需重复加密")
	}

	cipherText, err := cbc.Encrypt([]byte(s.Spec.ApiSecret), []byte(key))
	if err != nil {
		return err
	}

	base64Str := base64.StdEncoding.EncodeToString(cipherText)
	s.Spec.ApiSecret = fmt.Sprintf("%s%s", CIPHER_TEXT_PREFIX, base64Str)
	return nil
}

// 解密
func (s *Secret) DecryptAPISecret(key string) error {
	// 判断文本是否已经是明文
	if !strings.HasPrefix(s.Spec.ApiSecret, CIPHER_TEXT_PREFIX) {
		return fmt.Errorf("文本本身就是明文，无法解密")
	}

	base64CipherText := strings.TrimPrefix(s.Spec.ApiSecret, CIPHER_TEXT_PREFIX)

	cipherText, err := base64.StdEncoding.DecodeString(base64CipherText)
	if err != nil {
		return err
	}

	planText, err := cbc.Decrypt([]byte(cipherText), []byte(key))
	if err != nil {
		return err
	}

	s.Spec.ApiSecret = string(planText)
	return nil
}
